import os
import time

import pytest

from utils.dingtalk import dingTalk
from utils.logger import log
from utils.yamltool import BasePath, ExtractDataPath


@pytest.fixture(scope="session", autouse=True)
def clear_extract_data(request):
	with open(ExtractDataPath, 'w') as f:
		f.truncate()


# # 后置处理
# def pytest_sessionfinish(session, exitstatus):
# 	print("session finished: ", exitstatus, session)
# 	dingTalk.send_msg()

def pytest_terminal_summary(terminalreporter, exitstatus, config):
	"""
	收集结果数据
	:param terminalreporter: 内部终端报告对象, 对象的stats属性
	:param exitstatus: 报告操作系统的退出状态
	:param config: pytest配置
	:return:
	"""
	case_total = terminalreporter._numcollected
	print(f'执行测试用例总数: {case_total}')

	pass_total = len(terminalreporter.stats.get('passed', []))
	print(f'测试用例通过总数: {pass_total}')

	failed_total = len(terminalreporter.stats.get('failed', []))
	print(f'测试用例失败总数: {failed_total}')

	error_total = len(terminalreporter.stats.get('error', []))
	print(f'测试用例错误总数: {error_total}')

	skipped_total = len(terminalreporter.stats.get('skipped', []))
	print(f'测试用例跳过总数: {skipped_total}')

	duration = time.time() - terminalreporter._sessionstarttime
	print(f'测试用例执行时长: {duration}s')

	msg = f'执行测试用例总数: {case_total}\n' \
	      + f'测试用例通过总数: {pass_total}\n' \
	      + f'测试用例失败总数: {failed_total}\n' \
	      + f'测试用例错误总数: {error_total}\n' \
	      + f'测试用例跳过总数: {skipped_total}\n' \
	      + f'测试用例执行时长: {duration}s\n' \
	      + f'报告地址: http://192.168.1.220:8080/job/apitest/allure/\n'

	log.info(f'钉钉发送结果: {dingTalk.send_msg(msg)}')
